package cn.geminis.crypto.cert.service.service;

import cn.geminis.crypto.core.x509.X509Certificate;
import cn.geminis.crypto.csp.AbstractCspFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author puddi
 */
@Service
public class InstitutionServiceImpl implements InstitutionService {

    @Autowired
    private AbstractCspFactory cspFactory;

    private X509Certificate institutionCert;

    @Override
    public X509Certificate getCert() {
        if (Objects.isNull(institutionCert)) {
            institutionCert = new X509Certificate();
            institutionCert.setSerialNumber(BigInteger.ONE);
            institutionCert.setSubject("cn=ca");
            institutionCert.setNotBefore(LocalDateTime.now());
            institutionCert.setNotAfter(LocalDateTime.now());

            try (var signer = this.cspFactory.createSigner()) {
                institutionCert.setPublicKey(signer.getPublicKey());
                institutionCert.generate(signer);
            } catch (IOException e) {
                throw new RuntimeException("产生机构证书错误", e);
            }
        }

        return this.institutionCert;
    }
}
